import peewee
from datetime import datetime, timedelta

# 定义源数据库和目标数据库的连接信息
source_db = peewee.MySQLDatabase(
    'source_db_name',  # 源数据库名称
    user='your_username',  # 用户名
    password='your_password',  # 密码
    host='localhost',  # 主机
    port=3306  # 端口
)

target_db = peewee.MySQLDatabase(
    'target_db_name',  # 目标数据库名称
    user='your_username',  # 用户名
    password='your_password',  # 密码
    host='localhost',  # 主机
    port=3306  # 端口
)

# 定义模型
class BaseModel(peewee.Model):
    class Meta:
        database = source_db  # 默认使用源数据库

class Record(BaseModel):
    data = peewee.CharField()
    created_at = peewee.DateTimeField()

# 定义目标模型
class TargetRecord(BaseModel):
    data = peewee.CharField()
    created_at = peewee.DateTimeField()

    class Meta:
        database = target_db  # 使用目标数据库

# 创建表
source_db.connect()
source_db.create_tables([Record], safe=True)

target_db.connect()
target_db.create_tables([TargetRecord], safe=True)

# 转存数据的函数
def transfer_old_records(days_threshold):
    # 计算阈值时间
    threshold_time = datetime.now() - timedelta(days=days_threshold)

    # 查询超过阈值的记录
    old_records = Record.select().where(Record.created_at < threshold_time)

    # 开始转存和清除
    with target_db.atomic(), source_db.atomic():
        for record in old_records:
            # 转存到目标数据库
            TargetRecord.create(data=record.data, created_at=record.created_at)
            # 从源数据库中删除
            record.delete_instance()

    print(f"Transferred and deleted records older than {days_threshold} days.")

# 示例：转存超过7天的数据
transfer_old_records(7)

# 关闭数据库连接
source_db.close()
target_db.close()